package com.common.completableFuture;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.function.BiFunction;

/**
 * 当发生异常时返回自定义的值
 * @author zdh
 */
@Builder
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class DefaultValueHandle<R> extends LogAction<R> implements BiFunction<R, Throwable, R> {
    private  R defaultValue;
    /**
     * 当返回值为空的时候是否替换为默认值
     */
    private  boolean isNullToDefault;


    @Override
    public R apply(R result, Throwable throwable) {
        logResult(result, throwable);
        //发生异常,返回默认值
        if (throwable != null) {
            return defaultValue;
        }
        //返回值为空,此时需要在设置isNullToDefault为true的情况下,才会返回默认自
        if (result == null && isNullToDefault) {
            return defaultValue;
        }
        return result;
    }
}